package com.example.shixun1.renttest.main.utils;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.widget.RadioGroup;

import java.util.ArrayList;


public class FragmentTabUtils implements RadioGroup.OnCheckedChangeListener {
	private ArrayList<Fragment> fragments;

	private RadioGroup rgs;

	private FragmentManager fragmentManager;

	private int containerId;

    //private Bundle bundle=new Bundle();

	public FragmentTabUtils(ArrayList<Fragment> fragments, RadioGroup rgs,
                            FragmentManager fragmentManager, int containerId) {
		this.fragments = fragments;
		this.rgs = rgs;
		this.fragmentManager = fragmentManager;
		this.containerId = containerId;
		// 显示首页
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		transaction.add(containerId, fragments.get(0));
		transaction.show(fragments.get(0));
		//fragments.get(0).setArguments(bundle);
		transaction.commit();
		rgs.setOnCheckedChangeListener(this);
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		for (int i = 0; i < group.getChildCount(); i++) {
			Fragment fragment = fragments.get(i);
			if (checkedId == group.getChildAt(i).getId()) {
				addFragment(fragment);
			} else {
				FragmentTransaction transaction = fragmentManager
						.beginTransaction();
				transaction.hide(fragment);
				transaction.commitAllowingStateLoss();
			}
		}

	}
	/**
	 * 添加fragment
	 * 
	 * @param fragment
	 */
	private void addFragment(Fragment fragment) {
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		if (!fragment.isAdded()) {
			transaction.add(containerId, fragment);
			// 排队
		}
		transaction.show(fragment);
		transaction.commitAllowingStateLoss();
	}
}
